package com.asia5b.a5mall.middleware.base

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

/**
 * Created by zhangyuncai on 2019/12/2.
 * 生命周期的监听
 */
class SimpleLifecycleObserver() : DefaultLifecycleObserver {
    val lifecycleCalls by lazy { ArrayList<((state: Int) -> Unit)>() }

    override fun onCreate(owner: LifecycleOwner) {
        lifeCycleDo(LIFE_CYCLE_CREATE)
    }

    override fun onResume(owner: LifecycleOwner) {
        lifeCycleDo(LIFE_CYCLE_RESUME)
    }


    override fun onPause(owner: LifecycleOwner) {
        lifeCycleDo(LIFE_CYCLE_PAUSE)
    }

    override fun onDestroy(owner: LifecycleOwner) {
        lifeCycleDo(LIFE_CYCLE_DESTORY)
        lifecycleCalls.clear()
    }


    /**
     * @Note   在各个生命周期监听执行
     * @param  state 生命周期状态
     */
    private fun lifeCycleDo(state: Int) {
        lifecycleCalls.forEach { item ->
            item.invoke(state)
        }
    }

    fun add(listener: (state: Int) -> Unit) {
        if (!lifecycleCalls.contains(listener)) {
            lifecycleCalls.add(listener)
        }
    }

}